"""
支付相关API路由模块
提供支付创建和支付回调处理的接口
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session
from typing import Dict, Any
from app.database import get_db
from app.services.payment_service import PaymentService
from app.services.order_service import OrderService


# 创建支付相关的API路由器
router = APIRouter(prefix="/payments", tags=["payments"])
"""支付API路由器，所有支付相关接口前缀为/payments，标签为payments"""


@router.post("/{order_number}")
def create_payment(order_number: str, payment_data: Dict[str, Any], db: Session = Depends(get_db)):
    """
    创建支付接口
    根据订单号和支付方式创建相应的支付
    
    Args:
        order_number (str): 订单编号
        payment_data (Dict[str, Any]): 支付数据，包含payment_method字段
        db (Session): 数据库会话，通过依赖注入获取
    
    Returns:
        Dict[str, Any]: 支付创建结果
    
    Raises:
        HTTPException: 当订单不存在时返回404错误
        HTTPException: 当创建支付失败时返回400错误
    """
    # 初始化服务实例
    order_service = OrderService(db)
    payment_service = PaymentService(db)
    
    # 查询订单是否存在
    order = order_service.get_order_by_number(order_number)
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 创建支付，捕获可能的异常
    try:
        return payment_service.create_payment(order, payment_data["payment_method"])
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/callback/{payment_method}")
def payment_callback(payment_method: str, callback_data: Dict[str, Any], db: Session = Depends(get_db)):
    """
    支付回调接口
    处理支付平台的异步通知，验证签名并更新订单状态
    
    Args:
        payment_method (str): 支付方式，如alipay、wechat等
        callback_data (Dict[str, Any]): 回调数据
        db (Session): 数据库会话，通过依赖注入获取
    
    Returns:
        Dict[str, str]: 处理结果
    
    Raises:
        HTTPException: 当签名验证失败时返回400错误
        HTTPException: 当处理回调失败时返回400错误
    """
    # 初始化支付服务
    payment_service = PaymentService(db)
    
    # 处理回调，验证签名并更新状态
    try:
        if payment_service.verify_payment_callback(payment_method, callback_data):
            payment_service.handle_payment_success(callback_data.get("payment_number"))
            return {"status": "success"}
        else:
            raise HTTPException(status_code=400, detail="签名验证失败")
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))